package com.moyq5.mvc.framework.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

import javax.persistence.Embedded;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 实体属性赋默认值
 * @author   莫勇强
 * @date     2015-11-10上午11:52:31
 * @type     types
 * @function
 */
public class EntityUtils {
	private static Logger log = LoggerFactory.getLogger(EntityUtils.class);

	public static final long LONG_NULL = -1L;
    public static final int INT_NULL = -1;
    public static final String STRING_NULL = "-1";
	
	public static <T> T combine(T from, T to) {
		List<Field> fields = getFeilds(to.getClass());
		for (Field field : fields) {
			try {
				if (field.getType() == Set.class 
						|| Modifier.isFinal(field.getModifiers())
						|| Modifier.isStatic(field.getModifiers())) {
					continue;
				}
				field.setAccessible(true);
				Object value = field.get(from);
				if (null != value) {
					if (null != field.getAnnotation(Embedded.class)) {
						combine(value, field.get(to));
					} else if (value instanceof String && String.valueOf(value).equals(STRING_NULL)) {
						field.set(to, null);
					} else if (value instanceof Long && (Long)value == LONG_NULL) {
						field.set(to, null);
					} else if (value instanceof Integer && (Integer)value == INT_NULL) {
						field.set(to, null);
					} else {
						field.set(to, value);
					}
				}
			} catch (Exception e) {
				log.warn(e.getMessage(), e);
			}
		}
		return to;
	}
	
	public static <E> List<Field> getFeilds(Class<?> clazz) {
		List<Field> list = new ArrayList<Field>();
		Field[] fields = clazz.getDeclaredFields();
		if (fields.length > 0) {
			Collections.addAll(list, fields);
		}
		Class<?> superClazz;
		if ((superClazz = clazz.getSuperclass()) != Object.class) {
			List<Field> superFields = getFeilds(superClazz);
			if (superFields.size() > 0) {
				list.addAll(superFields);
			}
		}
		return list;
	}
}
